package com.anasoft.os.s4j;

import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.HttpCommandProcessor;

/**
 * Extension of {@link DefaultSelenium} that allows retrieving
 * the current Selenium session ID.
 * 
 * @see SeleniumSessionManager
 * 
 * @author vojtech.szocs
 */
public class SessionAwareDefaultSelenium extends DefaultSelenium {

    public SessionAwareDefaultSelenium(String serverHost, int serverPort, String browserStartCommand, String browserURL) {
        super(new SessionAwareCommandProcessor(serverHost, serverPort, browserStartCommand, browserURL));
    }
    
    public String getSessionId() {
        SessionAwareCommandProcessor processor = (SessionAwareCommandProcessor) commandProcessor;
        
        if (processor.hasSessionInProgress())
            return processor.getSessionId();
        else
            return null;
    }
    
    private static class SessionAwareCommandProcessor extends HttpCommandProcessor {
        
        private String sessionId;
        
        public SessionAwareCommandProcessor(String serverHost, int serverPort,
                String browserStartCommand, String browserURL) {
            super(serverHost, serverPort, browserStartCommand, browserURL);
        }
        
        @Override
        protected void setSessionInProgress(String result) {
            super.setSessionInProgress(result);
            this.sessionId = result;
        }
        
        public String getSessionId() {
            return sessionId;
        }
        
    }
    
}
